<?php

if($this->GetConfig('secure_login')==1){
	if(empty($_SERVER['HTTPS']) && substr(THIS_PAGE_URL, 0, 7)=='http://'){
		Antz::redir(str_replace('http://', 'https://', THIS_PAGE_URL));
	};
};

if(Antz_IntelliForm::submitted('login')){
    // begin checking
    $error = false;
    $username = post('username');
    $email = post('email');
    $password = post('password');
    $username = preg_replace('/[^a-zA-Z0-9\-_ ]/', '', $username);
    $uData = false;

    if($this->GetConfig('email_login')==1){
    	// login by email
    	$emailMD5 = md5(strtolower($email));
    	if($DB->countRows(cms_db_prefix().'iusers', "email_md5 = '{$emailMD5}'")==0){
    		$error = true;
    		Antz::addFormError('email', $this->Lang('not_registered'));
    	}else{
    		// email exists
	        $uData = $DB->fetchRow('SELECT * FROM '.cms_db_prefix()."iusers WHERE email_md5 = '{$emailMD5}'");
	        if($CRYPT->decrypt($uData['pass']) != $password){
	            $error = true;
	            Antz::addFormError('password', $this->Lang('incorrect_password'));
	        };
    	}
    }else{
	    // login by username
	    if($DB->countRows(cms_db_prefix().'iusers', "username = '{$username}'")==0){
	        $error = true;
	        Antz::addFormError('username', $this->Lang('not_registered'));
	    }else{
	        // username exists
	        $uData = $DB->fetchRow('SELECT * FROM '.cms_db_prefix()."iusers WHERE username = '{$username}'");
	        if($CRYPT->decrypt($uData['pass']) != $password){
	            $error = true;
	            Antz::addFormError('password', $this->Lang('incorrect_password'));
	        };
	    };
    };
	// hookup to other modules
	$hookParams = array(
		'error' => false,
		'errors' => array(),
		'user_data' => $uData
	);
	$newParams = Antz::Hookup('IUsers_LoginCheck', $hookParams);
	$hookParams = $newParams['params'];
	unset($newParams);
	if($hookParams['error']){
		$error = true;
		if(count($hookParams['errors'])>0){
			foreach($hookParams['errors'] as $errorMsg){
				Antz::addError($errorMsg);
			};
		};
	};

    if($uData['status']!=1){
        switch($uData['status']){
            case '2':
                $error = true;
                Antz::addError($this->Lang('pending_email_confirmation'));
            break;
            case '0':
                $error = true;
                Antz::addError($this->Lang('account_closed'));
            break;
            default:
                
        }
    }

    if(!$error){
        // ok to process login
        $USER->login($uData);
        if(post('persistent')=='1'){
            // set cookie for persistent login
            $hashCookie = md5(rand());
            setcookie($this->GetConfig('cookie_name').'_userid', $uData['id'], time()+86400*$this->GetConfig('cookie_lifetime'));
            setcookie($this->GetConfig('cookie_name').'_hash', $hashCookie, time()+86400*$this->GetConfig('cookie_lifetime'));
            $DB->update(cms_db_prefix().'iusers', array('cookie_hash'=>$hashCookie), "id = '{$uData['id']}'");
        }

        if(get('return_url')!=''){
            $returnUrl = get('return_url');
        }else{
            $returnUrl = Antz::getLastPage();
        }

		// add login hooks
		$hookParams = $uData;
		$newParams = Antz::Hookup('IUsers_LoginProcess', $hookParams);
		unset($newParams);


        // SMF integration
        if(is_object($this->IUsers2SMF) && $this->IUsers2SMF instanceof IUsers2SMF){
            $smfParams = array(
                'username' => $username,
                'password' => $password
            );
            $this->IUsers2SMF->login($smfParams, $returnUrl);
        }// end SMF integration

        // only get here if smf not enabled
        Antz::redir($returnUrl);

    }
};// end if submitted




// gonna define the form fields as an array because other modules can add their fields to it (See Antz::Hookup())
$formFields = array();
if($this->GetConfig('email_login')==1){
	$formFields[] =
	array(
		'name' => 'email',
		'value' => post('email'),
		'type' => 'text',
		'label' => $this->Lang('email'),
		'required' => true
	);
}else{
	$formFields[] =
	array(
		'name' => 'username',
		'value' => post('username'),
		'type' => 'text',
		'label' => $this->Lang('username'),
		'required' => true
	);
}
$formFields[] = array(
	'name' => 'password',
	'value' => post('password'),
	'type' => 'password',
	'label' => $this->Lang('password'),
	'required' => true
);



// implement the hook to get extra form fields from other modules
$hookParams = array(
    'form_fields' => $formFields
);
$newParams = $Antz->Hookup('IUsers_LoginFormFields', $hookParams);
$formFields = $newParams['params']['form_fields'];
unset($newParams);

// ready to create our form

if($this->GetConfig('auto_forms')){

	// prepare the structure for auto form generation
	$blocks = array(
		0 => array(
			'type' => 'full',
			'fieldsets' => array(
				0 => array(
					'legend' => $this->Lang('login_legend'),
					'side' => 'left',
					'fields' => $formFields
				)
			)
		)
	);

	$form = Antz::makeForm($blocks, 'login');

	$form->addSubmit($this->Lang('login'));

	echo $form->render();

}else{
	// assigning form components to smarty variables and processing template
	if($this->GetConfig('wrap_form_components')) $wrap = true;
	else $wrap = false;
	if($this->GetConfig('show_labels')) $labels = true;
	else $labels = false;

	foreach($formFields as $field){
		$component = Antz::makeFormComponent($field, $wrap, $labels);
		$this->smarty->assign('fc_'.$field['name'], $component->render());
	};

	$this->smarty->assign('login_intelliform_seed', Antz_IntelliForm::seed('login'));

	echo $this->ProcessTemplate('login.tpl');

}



/*
// build the login form
$form = Antz::newObject('Antz_Form', __FILE__);
$form->setId('login-form');
$block = $form->add('full');
$fs = $block->add($this->Lang('login_details'));
$fs->addInput('text', 'username', $this->Lang('username'), post('username'));
$fs->addInput('password', 'password', $this->Lang('password'), post('password'));
$chk = $fs->addCheckboxGroup('persist');
$chk->add('persistent', $this->Lang('persistent'), '1', post('persistent', false));
$fs->addInput('submit', 'submitBtn', '&nbsp;', $this->Lang('login'));

echo $form->render();
*/
